package com.adouteam.simple.wechat.service;

import com.adouteam.simple.wechat.base.Constant;
import com.adouteam.simple.wechat.base.WechatConstants;
import com.adouteam.simple.wechat.tool.Encrypt;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * 接入服务
 *
 * @author buxianglong
 */
public class AccessService{
    private static final Logger logger = LoggerFactory.getLogger(AccessService.class);

    /**
     * 检查接入
     *
     * @param wechatConstants 微信配置参数
     * @param signature       微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp       时间戳
     * @param nonce           随机数
     * @param echostr         随机字符串
     * @return true：接入成功；false：接入失败
     */
    public static boolean check(WechatConstants wechatConstants, String signature, String timestamp, String nonce, String echostr){
        String token = wechatConstants.getAppToken();
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        String[] array = {token, timestamp, nonce};
        Arrays.sort(array);
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        String join = StringUtils.join(array);
        String encryptJoin = Encrypt.encryptSHA1(join);
        // 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        logger.debug(Constant.LOGGER_PREFIX + "encryptJoin:" + encryptJoin);
        logger.debug(Constant.LOGGER_PREFIX + "signature:" + signature);
        return StringUtils.equalsIgnoreCase(encryptJoin, signature);
    }
}
